package downloader

import (
	"bytes"
	"fmt"
	"image"
	"os"
	"path/filepath"

	"github.com/chai2010/webp"
)

// WebPConverter 处理WebP格式转换
type WebPConverter struct {
	Lossless bool
	Quality  float32
}

// NewWebPConverter 创建新的WebP转换器
func NewWebPConverter(lossless bool, quality float32) *WebPConverter {
	return &WebPConverter{
		Lossless: lossless,
		Quality:  quality,
	}
}

// ConvertToWebP 将图片数据转换为WebP格式并保存
func (c *WebPConverter) ConvertToWebP(imgData []byte, outputPath string) error {
	img, format, err := image.Decode(bytes.NewReader(imgData))
	if err != nil {
		return fmt.Errorf("解码图片失败: %v", err)
	}
	fmt.Printf("检测到图片格式: %s\n", format)

	dir := filepath.Dir(outputPath)
	if err := os.MkdirAll(dir, 0755); err != nil {
		return fmt.Errorf("创建目录失败: %v", err)
	}

	outputFile, err := os.Create(outputPath)
	if err != nil {
		return fmt.Errorf("创建输出文件失败: %v", err)
	}
	defer outputFile.Close()

	options := &webp.Options{
		Lossless: c.Lossless,
		Quality:  c.Quality,
	}

	if err := webp.Encode(outputFile, img, options); err != nil {
		return fmt.Errorf("编码为webp失败: %v", err)
	}

	fmt.Printf("成功转换并保存为: %s\n", outputPath)
	return nil
}
